import { toRaw } from 'vue'
export const isBooleanString=(value)=> {
  return ['true', 'false'].includes(String(value).toLowerCase())
}
export const isProxy=(obj)=> {
  return obj !== null && typeof obj === 'object' && toRaw(obj) !== obj;
}
export const processIfProxy=(obj)=> {
   const raw = toRaw(obj) 
   if(!isProxy(raw)){
       return raw
   }
     return processIfProxy(raw)
}
export const isEmpty=(value)=> {
  isProxy(value) && (value = processIfProxy(value));

  if (value === null || value === undefined) return true

  if (typeof value === 'string') {
    return value.trim() === ''
  }

  if (Array.isArray(value)) {
    return value.length === 0
  }

  if (typeof value === 'object') {
    return Object.keys(value).length === 0
  }

  if (typeof value === 'number') {
    return isNaN(value)
  }

  return false
}

export const parseValue=(value)=> {
  if (typeof value !== 'string') return value

  const lower = value.trim().toLowerCase()
  if (lower === 'true') return true
  if (lower === 'false') return false
  return value
}
export const ensureArray=(val)=> {
  if (Array.isArray(val)) return val;
  if (typeof val === 'string') return val.split(',').filter((v) => v.trim());
  return [];
}

export const deepClone = (origin)=> {
    if (origin === undefined) {
        return undefined
    }

    return JSON.parse(JSON.stringify(origin))
}

export const extractFirstParenthesesContent=(sql)=> {
    let startIdx = -1;
    let depth = 0;

    for (let i = 0; i < sql.length; i++) {
        const char = sql[i];

        if (char === '(') {
            if (startIdx === -1) {
                startIdx = i + 1; // 第一个左括号后开始提取
            }
            depth++;
        } else if (char === ')') {
            depth--;
            if (depth === 0 && startIdx !== -1) {
                return sql.substring(startIdx, i).trim(); // 提取成功，返回
            }
        }
    }

    return null; // 没有找到匹配的括号对
}
export const inferDataType=(value)=> {
    if (typeof value === 'number' || /^-?\d+$/.test(value)) {
        return 'number';
    } else if (typeof value === 'string' && /^'.*'$/.test(value)) {
        // 判断是否为字符串形式（例如：'name_331'）
        return 'text';
    } else if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
        // 判断是否为日期格式（YYYY-MM-DD）
        return 'date';
    } else {
        return 'text';
    }
}
export const extractFieldsFromSql=(sql='')=> {
    const fields = [];

    const sql1 = sql.trim().toUpperCase();
    if (sql1.startsWith('CREATE TABLE')) {
        //console.log(sql) 
        const tempsql = extractFirstParenthesesContent(sql);
        //console.log('tempsql:', tempsql);
        const tempcolumns = tempsql.split(',');
        //console.log('tempcolumns:', tempcolumns);
        const regex = /`(\w+)`\s+(\w+(?:\d+)?\)?)([^,]*?)(?:\s+COMMENT\s+'([^']*)')?/i; //不知道什么原因提取不了注释
        tempcolumns.forEach((item,index)=>{
            const match = item.match(regex);
            if(match){
                //const [fieldName,fieldType] = match[0].split(' ');
                const fieldName = match[1];
                const fieldType = match[2];
                let comment = fieldName
                let dataType = 'text';
                if (/INT|INTEGER/i.test(fieldType)) {
                    dataType = 'number';
                } else if (/VARCHAR|CHAR|TEXT/i.test(fieldType)) {
                    dataType = 'text';
                } else if (/DATE|DATETIME|TIMESTAMP/i.test(fieldType)) {
                    dataType = 'date';
                }
                // 重新提取注释
                const match1 = item.match(/\bCOMMENT\s+'([^']*)'/i);
                if(match1){
                    comment = match1[1];
                }
                fields.push({ columnId:index, prop: fieldName, label: comment, visible: true, searchable: true, fieldOptions:{type: dataType} });
            }            
        })
    } else if (sql1.startsWith('INSERT INTO')) {
        // 匹配 INSERT INTO 的字段名  SQL里 大写关键词
        const columnNamesMatch = sql.match(/INSERT\s+INTO\s+.*?\((.*?)\)\s+VALUES\s*\((.*?)\)/i); //(/INSERT\s+INTO\s+.*?\((.*?)\)\s+VALUES\s*\((.*?)\)/i);
        //console.log('columnNamesMatch:', columnNamesMatch);
        if (columnNamesMatch) {
            const columnNames = columnNamesMatch[1].split(',').map(a => a.trim().replace(/`/g, ''));
            const values = columnNamesMatch[2].split(',').map(a => a.trim()).map(value => {
        // 去除字符串两边的单引号
                if (/^'.*'$/.test(value)) {
                    return value.slice(1, -1); // 字符串去掉引号
                } else if (!isNaN(value)) {
                    return Number(value); // 转换为数字
                } else {
                    return value; // 其他情况作为普通字符串返回
                }
            });
            columnNames.forEach((name, index) => {
                let value = values[index];
                const dataType = inferDataType(value); // 推断数据类型
                fields.push({ columnId:index, prop: name, label: name, visible: true, searchable: true, fieldOptions:{type: dataType} });
            });
        }
    } else if (sql1.startsWith('UPDATE')) {
        // 匹配 UPDATE 的字段名
        const setClauseMatch = sql.match(/(?<=SET|set|Set)\s+(.+?)\s+(WHERE|where|Where)/i);//(/SET\s+(.+?)\s+WHERE/i); // 没有提取ID等key字段
        //console.log('setClauseMatch:', setClauseMatch);
        if (setClauseMatch) {
            const assignments = setClauseMatch[1].split(',').map(a => a.trim());
            //console.log('assignments:', assignments);
            assignments.forEach(assignment => {
                const [field,value] = assignment.split('=').map(part => part.trim().replace(/`/g, '').replace(' ', '').replace(/\'/g, ''));
                const fieldName = field;
                const dataType = inferDataType(value);
                fields.push({ columnId: Date.now(), prop: fieldName, label: fieldName, visible: true, searchable: true, fieldOptions:{type: dataType} });
            });
        }
    }
    //console.log('提取字段:', fields);
    return fields;
}

export const generateTestData=(fields,recordCout)=> {
    if(!fields || fields.length === 0) return [];
    const testDatas = [];
    for (let i = 0; i < recordCout; i++) {
        const testData = {};
        fields.forEach(({ prop, fieldOptions }) => {
            switch (fieldOptions.type) {
                case 'number':
                    testData[prop] = Math.floor(Math.random() * 1000);
                    break;
                case 'text':
                    testData[prop] = `${prop}_${Math.random().toString(36).substring(2, 8)}`;
                    break;
                case 'date':
                    testData[prop] = new Date().toISOString().split('T')[0];
                    break;
                default:
                    testData[prop] = null;
            }
        });
        testDatas.push(testData);
    }

    return testDatas;
}

export function processSqlAndGenerateTestData(sql='',recordCout=15) {
    const fields = extractFieldsFromSql(sql);       
    const testDatas = generateTestData(fields,recordCout);
    return { columns: [...fields,{ 
                                    columnId: Date.now(), 
                                    prop: 'action', 
                                    type: 'action', 
                                    label: '操作', 
                                    slot: 'action', 
                                    width: 180,
                                    visible:true,
                                    resizable:true 
                                }], 
            data: testDatas 
        };
}
/*
// 示例用法
const sqlStatements = [
    "CREATE TABLE db_test ( ID int(10) UNSIGNED NOT NULL AUTO_INCREMENT, NAME varchar(50) CHARACTER SET gbk COLLATE gbk_chinese_ci NULL DEFAULT '', PRIMARY KEY (ID) USING BTREE )",
    "UPDATE HC_DB.db_test SET NAME = 'name_225' WHERE ID = 3",
    "INSERT INTO HC_DB.db_test (ID, NAME) VALUES (2, 'name_331')"
];

const result = processSqlAndGenerateTestData(sqlStatements);
console.log('提取字段:', result.fields);
console.log('生成的测试数据:', result.testDataSet);
*/